<template>
  <div class="column-resizer">
    <div
      v-for="(w, index) in widths"
      :key="index"
      class="column-resizer__item"
      :class="{ 'is-resizing': state.index === index }"
      :style="{ marginLeft: `${w}px` }"
      @mousedown.left.stop="resizer.dragStart($event, index)"
    >
      <div class="column-resizer__handle" :style="state.index === index ? `left: ${offset}px` : ''"></div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, reactive, set } from 'vue'
import { Widget } from '@/models'
import { TableColWidths } from '@/types'
import { useDrag } from '@/utils'
import config from '@/config'

export default defineComponent({
  name: 'ColumnResizer',

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 表格列宽 */
    widths: {
      type: Array as PropType<TableColWidths>,
      required: true
    }
  },

  setup(props) {
    const defaultState = {
      /** 列索引 */
      index: -1,
      /** 移动像素 */
      move: 0
    }

    /** 调整状态 */
    const state = reactive({ ...defaultState })

    /** 调整宽度 */
    const resizer = useDrag<number, number>({
      onStart(e, index) {
        if (index === undefined) return false

        state.index = index

        return index
      },

      onMoving(e, { x }, index) {
        const { widths, data: widget } = props

        const minX = config.tableOption.colWidthMin - widths[index]

        const maxX = (widget.page?.w || config.page.width) - widget.x - widget.w

        if (x < minX) x = minX
        if (x > maxX) x = maxX

        state.move = x
      },

      onEnd() {
        const { index, move } = state
        const { widths, data: widget } = props
        const width = Math.floor(widths[index] + move)

        widget.setTableColWidth(index, width)

        Object.assign(state, defaultState)
      }
    })

    return {
      /** 调整状态 */
      state,

      /** 调整宽度 */
      resizer,

      /** 移动偏移 */
      offset: computed(() => {
        const widget = props.data
        const { index, move } = state
        const w = props.widths[index]

        const min = config.tableOption.colWidthMin - w
        const max = (widget.page?.w || config.page.width) - widget.x - widget.w

        if (move < min) return min

        if (move > max) return max

        return move
      })
    }
  }
})
</script>

<style lang="scss">
.fa-widget-table-main .column-resizer {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  width: 0;
  height: 100%;

  &__item {
    position: relative;
    flex: none;
    width: 0;
    height: 100%;
    cursor: col-resize;

    &.is-resizing .column-resizer__handle {
      border-right: 1px solid rgba(#000, 0.4);
    }
  }

  &__handle {
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    margin-left: -4px;
  }
}
</style>
